//
//  ImagePreviewViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/23.
//

import UIKit
import Kingfisher
import SnapKit
import PKHUD


/// 图片预览控制器
class ImagePreviewViewController: BaseViewController,UIScrollViewDelegate {

    var contentScrollerView:UIScrollView!
    var imageView:UIImageView!
    var imageUrl:String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        contentScrollerView = UIScrollView(frame: view.bounds)
        if #available(iOS 13.0, *) {
            contentScrollerView.backgroundColor = .systemGray5
        } else {
            contentScrollerView.backgroundColor = .white
        }
        contentScrollerView.maximumZoomScale = 3
        contentScrollerView.minimumZoomScale = 1
        contentScrollerView.bounces = true
        contentScrollerView.delegate = self
        view.addSubview(contentScrollerView)
    
        imageView = UIImageView()
        imageView?.contentMode = .scaleAspectFit
        imageView.isUserInteractionEnabled = true
        contentScrollerView.addSubview(imageView)
    
        HUD.show(.progress)
        
        let image_url = imageUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        guard let url = URL(string: image_url!) else {
            HUD.hide()
            HUD.flash(.label("网络错误"), delay: 1.0)
            return
        }
        
        KingfisherManager.shared.downloader.downloadImage(with: url,
                                                          retrieveImageTask: .none,
                                                          options: nil,
                                                          progressBlock: .none) { (image, err, url, data) in
            HUD.hide()
            if err != nil {
                HUD.flash(.label(err!.description), delay: 1.0)
            }else {
                self.setupImage(image: image!)
            }
        }
        
       
    }
    
    func setupImage(image: UIImage){
        
        let radio = image.size.width / image.size.height
        let w = view.bounds.width
        let h = w / radio
        
        imageView.image = image
        imageView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalTo(w)
            make.height.equalTo(h)
        }
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    init(url:String) {
        super.init(nibName: nil, bundle: nil)
        self.imageUrl = url
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}
